import json
from django.contrib.auth import login,logout
from users.forms import RegisterForm,LoginForm
from users.models import User
from utils.json_fun import to_json_data

from django.shortcuts import render,redirect,reverse

from django.views.decorators.csrf import ensure_csrf_cookie
from django.utils.decorators import method_decorator
# Create your views here.
from django.views import View

from utils.res_code import Code
import json
# 注册
class RegisterView(View):
    """
    /users/register/
    """
    def get(self,request):

        return render(request,'users/register.html')


    def post(self,request):

        # 1, 获取参数
        #2， 校验参数
        #3， 存入数据库
        #4， 给用户提示

        #1
        json_data = request.body
        if not json_data:
            return to_json_data(errno=Code.PARAMERR,errmsg="参数错误，请重新输入")

        dict_data = json.loads(json_data.decode('utf8'))

        # 2  parameter validation
        form = RegisterForm(data=dict_data)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            mobile = form.cleaned_data.get('mobile')

        # 3 save to mysql
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
            login(request, user)    # login向session中添加SESSION_KEY, 便于对用户进行跟踪:
            return to_json_data(errmsg='Welcome to the zhang family')
        else:
            err_msg_list = []
            for item in form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
            err_msg_str = '/'.join(err_msg_list)

            return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)

# 登录
class LoginView(View):

    # @method_decorator(ensure_csrf_cookie)
    def get(self,request):
        return render(request,'users/login.html')

    def post(self,request):
        json_data = request.body
        if not json_data:
            return to_json_data(json_data.decode('utf8'))

        dict_data = json.loads(json_data.decode('utf8'))

        form = LoginForm(data=dict_data,request=request)

        if form.is_valid():
            return to_json_data(errmsg='恭喜，登录成功')

        else:
            err_msg_list = []
            for item in form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
            err_msg_str = '/'.join(err_msg_list)  # 拼接错误信息为一个字符串

            return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)


# 登出
class LogoutView(View):

    def get(self,request):
        logout(request)

        return redirect(reverse('news:index'))








